from flask import Blueprint, request
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON
from common.models.study_list import StudyList
from common.models.study_order import StudyOrder
from common.models.study_comment import StudyComment
# from common.models.study_comment import StudyComment
from common.models.department import Department
from common.models.user import User
from common.models.project import Project
from application import db
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from flask import json
import datetime
from sqlalchemy import func
import requests
import urllib.request

study_page = Blueprint("study_page", __name__)


@study_page.route("/showstudylist", methods=["GET", "POST"])
def showstudylist():
    req = request.values
    city = req['city'] if "city" in req else ""
    nowyears = str(datetime.datetime.now().year)
    nowmonth = str(datetime.datetime.now().month)
    nowdate = nowyears + "-" + nowmonth + "-01"
    nowdate = datetime.datetime.strptime(nowdate, '%Y-%m-%d')

    a = StudyList.query.filter(StudyList.mark != 0, StudyList.city == city, StudyList.date >= nowdate).all()
    rts = []
    for item in a:
        stime = str(item.stime)
        etime = str(item.etime)
        date = str(item.date)
        temp = dict(name=item.name, company=item.company, department=item.department, teacher=item.teacher, id=item.id,
                    stime=stime, etime=etime, date=date)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@study_page.route("/showmylist", methods=["GET", "POST"])
def showMyList():
    req = request.values
    uid = req['uid'] if "uid" in req else ""

    a = StudyOrder.query.filter_by(uid=uid, mark=1).all()
    rts = []
    for item in a:
        date = str(item.studycourse.date)
        stime = str(item.studycourse.stime)
        etime = str(item.studycourse.etime)
        temp = dict(name=item.studycourse.name, id=item.id, date=date, stime=stime, etime=etime,
                    teacher=item.studycourse.teacher, company=item.studycourse.company,
                    department=item.studycourse.department,sid=item.sid)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@study_page.route('/poststudyorder', methods=['GET', 'POST'])
def poststudyorder():
    req = request.values
    name = req['name'] if "name" in req else ""
    company = req['company'] if "company" in req else ""
    department = req['department'] if "department" in req else ""
    teacher = req['teacher'] if "teacher" in req else ""
    city = req['city'] if "city" in req else ""
    length = req['length'] if "length" in req else ""
    stime = req['stime'] if "stime" in req else ""
    etime = req['etime'] if "etime" in req else ""
    date = req['date'] if "date" in req else ""

    if len(name) < 1:
        return ops_renderErrJSON(msg="请输入名称")
    if len(teacher) < 1:
        return ops_renderErrJSON(msg="请输入讲师")

    if len(company) < 1 or company == "请选择":
        return ops_renderErrJSON(msg="请选择公司名称")

    if len(department) < 1 or department == "请选择":
        return ops_renderErrJSON(msg="请选择部门")

    if len(date) < 1:
        return ops_renderErrJSON(msg="请选择日期")

    if len(stime) < 1:
        return ops_renderErrJSON(msg="请选择开始时间")

    if len(etime) < 1:
        return ops_renderErrJSON(msg="请选择结束时间")

    if len(length) < 1:
        return ops_renderErrJSON(msg="请填写课时")

    if len(city) < 1 or city == "请选择":
        return ops_renderErrJSON(msg="请选择城市")

    else:
        Order = StudyList()
        Order.name = name
        Order.company = company
        Order.department = department
        Order.city = city
        Order.teacher = teacher
        Order.stime = stime
        Order.etime = etime
        Order.length = length
        Order.date = date
        Order.mark = 1
        Order.created_time = Order.updated_time = getCurrentTime()

        db.session.add(Order)
        db.session.commit()

        return json.dumps({"code": 200, "msg": "添加成功", }, indent=4,
                          sort_keys=True, default=str,
                          ensure_ascii=False)


@study_page.route('/postenlist', methods=['GET', 'POST'])
def postEnlist():
    req = request.values
    sid = req['sid'] if "sid" in req else ""
    uid = req['uid'] if "uid" in req else ""

    if len(sid) < 1:
        return ops_renderErrJSON(msg="报名失败")
    if len(uid) < 1:
        return ops_renderErrJSON(msg="报名失败")

    else:
        a = StudyOrder.query.filter(StudyOrder.sid==sid, StudyOrder.uid==uid,StudyOrder.mark==1).first()

        if a:
            return ops_renderErrJSON(msg="您已报名过该课程")
        else:
            Order = StudyOrder()
            Order.sid = sid
            Order.uid = uid
            Order.mark = 1
            Order.created_time = Order.updated_time = getCurrentTime()

            db.session.add(Order)
            db.session.commit()

            return json.dumps({"code": 200, "msg": "添加成功", }, indent=4,
                              sort_keys=True, default=str,
                              ensure_ascii=False)


@study_page.route("/changemark", methods=["GET", "POST"])
def changemark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = StudyOrder.query.filter_by(id=id).first()
    a.mark = mark
    db.session.commit()
    return ops_renderJSON(msg="状态变更成功")


@study_page.route("/changelistmark", methods=["GET", "POST"])
def changelistmark():
    req = request.values
    id = req['id'] if "id" in req else ""
    mark = req['mark'] if "mark" in req else ""
    a = StudyList.query.filter_by(id=id).first()
    a.mark = mark
    db.session.commit()
    return ops_renderJSON(msg="状态变更成功")


@study_page.route("/showadminlist", methods=["GET", "POST"])
def showAdminList():
    req = request.values
    city = req['city'] if "city" in req else ""
    stime = req['stime'] if "stime" in req else ""
    etime = req['etime'] if "etime" in req else ""
    mark = req['mark'] if "mark" in req else ""

    if len(stime) < 1:
        return ops_renderErrJSON(msg="请输入开始时间")
    if len(etime) < 1:
        return ops_renderErrJSON(msg="请输入结束时间")
    else:
        a = StudyList.query.filter(StudyList.mark == mark, StudyList.city == city, StudyList.date <= etime,
                                   StudyList.date >= stime).all()
        rts = []
        for item in a:
            stime = str(item.stime)
            etime = str(item.etime)
            date = str(item.date)
            temp = dict(name=item.name, company=item.company, department=item.department, teacher=item.teacher,
                        id=item.id, stime=stime, etime=etime, date=date)
            rts.append(temp)
            # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
        return json.dumps(rts, ensure_ascii=False)  # rts


@study_page.route("/getstudydetail", methods=["GET", "POST"])
def getstudydetail():
    req = request.values
    id = req['id'] if "id" in req else ""
    a = StudyOrder.query.filter_by(sid=id, mark=1).all()
    rts = []
    for item in a:
        temp = dict(id=item.id, student=item.creater.nickname, company=item.creater.company,
                    department=item.creater.department, mark=item.mark)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@study_page.route("/getstudydetail2", methods=["GET", "POST"])
def getstudydetail2():
    req = request.values
    id = req['id'] if "id" in req else ""
    a = StudyOrder.query.filter_by(sid=id, mark=2).all()
    rts = []
    for item in a:
        temp = dict(id=item.id, student=item.creater.nickname, company=item.creater.company,
                    department=item.creater.department, mark=item.mark)
        rts.append(temp)
    # rts = json.dumps(a, cls=AlchemyEncoder,ensure_ascii=False)
    return json.dumps(rts, ensure_ascii=False)  # rts


@study_page.route('/postcomment', methods=['GET', 'POST'])
def postcomment():
    req = request.values
    score1 = req['score1'] if "score1" in req else ""
    score2 = req['score2'] if "score2" in req else ""
    score3 = req['score3'] if "score3" in req else ""
    score4 = req['score4'] if "score4" in req else ""
    score5 = req['score5'] if "score5" in req else ""
    score6 = req['score6'] if "score6" in req else ""
    score7 = req['score7'] if "score7" in req else ""
    comment1 = req['comment1'] if "comment1" in req else ""
    comment2 = req['comment2'] if "comment2" in req else ""
    comment3 = req['comment3'] if "comment3" in req else ""
    uid = req['uid'] if "uid" in req else ""
    sid = req['id'] if "id" in req else ""

    # sumscore = int(score1) + int(score2) + int(score3) + int(score4) + int(score5) + int(score6) + int(score7)
    sumscore=sum([int(score1),int(score2),int(score3),int(score4),int(score5),int(score6),int(score7)])
    if int(score1) < 1:
        return ops_renderErrJSON(msg="请打分")

    if int(score2) < 1:
        return ops_renderErrJSON(msg="请打分")

    if int(score3) < 1:
        return ops_renderErrJSON(msg="请打分")

    if int(score4) < 1:
        return ops_renderErrJSON(msg="请打分")

    if int(score5) < 1:
        return ops_renderErrJSON(msg="请打分")

    if int(score6) < 1:
        return ops_renderErrJSON(msg="请打分")

    if int(score7) < 1:
        return ops_renderErrJSON(msg="请打分")

    else:
        Order = StudyComment()
        Order.score1 = score1
        Order.score2 = score2
        Order.score3 = score3
        Order.score4 = score4
        Order.score5 = score5
        Order.score6 = score6
        Order.score7 = score7
        Order.sumscore = sumscore
        Order.comment1 = comment1
        Order.comment2 = comment2
        Order.comment3 = comment3
        Order.uid = uid
        Order.sid = sid
        Order.created_time = Order.updated_time = getCurrentTime()
        db.session.add(Order)
        db.session.commit()

        a = StudyOrder.query.filter_by(sid=sid,uid=uid).first()
        a.mark = 2
        db.session.commit()

        return json.dumps({"code": 200, "msg": "评价成功", }, indent=4,
                          sort_keys=True, default=str,
                          ensure_ascii=False)
